//
// Created by ct on 2020/10/27.
//

#include "packet_stats.h"
#include <algorithm>
#include <ifaddrs.h>
#include <list>
#include "utils.h"
#include <iostream>
namespace nettop {

    // 统计本地IP
    local_addr_mgr::local_addr_mgr() {
        struct ifaddrs *ifaddr = nullptr, *ifa = nullptr;
        int n=0;

        if(-1 == getifaddrs(&ifaddr))
            throw runtime_error("Failure in getifaddrs");
        for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
            if (ifa->ifa_addr == NULL)
                continue;
            const int family = ifa->ifa_addr->sa_family;
            // 获取适配器名字
            //std::cout<<"family: "<<ifa->ifa_name<<std::endl;
            if (family == AF_INET) {
                const struct sockaddr_in	*sa = (struct sockaddr_in*)ifa->ifa_addr;
                local_addrs_.insert(addr_t(sa->sin_addr));
              //std::cout<<  is_local(addr_t(sa->sin_addr)) << std::endl;
              //std::cout<<"sin_addr: "<< addr_t(sa->sin_addr).to_str() << std::endl;
            } else if(family == AF_INET6) {
                const struct sockaddr_in6	*sa = (struct sockaddr_in6*)ifa->ifa_addr;
                local_addrs_.insert(addr_t(sa->sin6_addr));
            }
        }
        freeifaddrs(ifaddr);
    }
    bool nettop::local_addr_mgr::is_local(const addr_t& in) const {
        return local_addrs_.find(in) != local_addrs_.end();
    }
}